<!--
 * @description  : 市管-特殊区域计划/检查列表
 * @descriptionDetail: 市管-特殊区域计划/检查列表
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-09-26 15:57:44
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
      <view class="nav-right-icon" v-if="tabIndex == 0">
        <u-icon name="plus" color="#FFF" @tap="handlerPlanDetail"></u-icon>
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- 企业微信集成 2023-11-9 fsx start -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="tabIndex== 0?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
		<!-- 企业微信集成 2023-11-9 fsx end -->
    <view class="content u-page">
      <view class="tabsBottom" v-show="tabIndex==0">
        <u-sticky>
          <u-cell-group class="sticky-header">
            <u-cell-item icon="calendar" title="开始/结束日期" :value="rangeDate" :arrow="true" @tap="dateRange=true">
            </u-cell-item>
          </u-cell-group>
        </u-sticky>
        <!-- 无证电子烟计划 上拉加载 -->
        <me-table
          :i="0"
          :index="0"
          :top="100"
          :load-data="loadPlanData"
          :init-load="false"
          ref="mescrollItem0"
        >
          <template #default="d">
            <view class="card">
              <u-swipe-action
                :show="d.data.show"
                :index="d.data.checkPlanUuid"
                :disabled="d.data.swiperDisabled"
                @click="swiperClick"
                @open="swiperOpen"
                :options="d.data.swiperOption"
              >
                <PlanItem :plan="d.data"></PlanItem>
              </u-swipe-action>
            </view>
          </template>
        </me-table>
      </view>
      <view class="tabsBottom" v-show="tabIndex==1">
        <u-sticky>
          <u-cell-group class="sticky-header">
            <u-cell-item icon="calendar" title="日期" :value="nowDay" :arrow="true" @tap="dateChoiceShow = true">
            </u-cell-item>
          </u-cell-group>
        </u-sticky>
        <!-- 特殊区域检查 -->
        <me-table
          :i="1"
          :index="1"
          :top="100"
          :load-data="queryCheckRecordList"
          :init-load="false"
          ref="mescrollItem1"
        >
          <template #default="d">
            <view class="card">
              <elecigare-check-item :client="d.data"></elecigare-check-item>
            </view>
          </template>
        </me-table>
      </view>
    </view>
    <u-calendar mode="range" max-date="2099-12-31" v-model="dateRange" @change="handlerSearchDate"></u-calendar>
    <u-calendar mode="date" max-date="2099-12-31" v-model="dateChoiceShow" @change="handlerSearchDay"></u-calendar>
    <u-tabbar :list="list" :active-color="$theme.u_type_primary" icon-size="40" bg-color="#F3F4F5" :mid-button="false" v-model="current" @change="tabsChange"></u-tabbar>
  </view>
</template>

<script>
import meTable from '@/components/me-table.vue'
import MescrollMoreMixin from "@/components/mescroll-uni/mixins/mescroll-more.js";
import checkService from "@/service/check/check.service";
import {dateUtils,} from "@/common/util";
import PlanItem from './components/plan-item.vue';
import AreasItem from './components/areas-item.vue';
import ElecigareCheckItem from './components/elecigare-check-item.vue';
import {M_PLAN_STATUS,M_COMMON_CHECK_STATUS,} from "@/service/check/mapping/enum.js";
// 企业微信集成 2023-11-9 fsx start
import fabButton from '@/components/uni-fab.vue';
// 企业微信集成 2023-11-9 fsx end
export default {
  components:{
    meTable,
    PlanItem,
    // AreasItem,
    ElecigareCheckItem,
		fabButton
  },
  mixins: [MescrollMoreMixin,],
  data() {
    return {
      M_PLAN_STATUS,
      M_COMMON_CHECK_STATUS,
      dateRange: false,
      rangeDate: dateUtils.dateFormat("yyyy-MM-dd", dateUtils.firstDate(new Date())) + "至" + dateUtils.dateFormat("yyyy-MM-dd", dateUtils.lastDate(new Date())),
      startDate: dateUtils.dateFormat("yyyy-MM-dd", dateUtils.firstDate(new Date())),
      endDate: dateUtils.dateFormat("yyyy-MM-dd", dateUtils.lastDate(new Date())),
      nowDay: this.$u.date(Date.now(),'yyyy-mm-dd'),
      current: 0,
      tabIndex: 0, // 表示当前活动的tab选项
      checkList: [],  // 检查列表数据(不分页)
      list: [{
        iconPath: "home",
        selectedIconPath: "home-fill",
        text: '计划',
        count: 0,
        isDot: false,
        customIcon: false,
      },
      {
        iconPath: "edit-pen",
        selectedIconPath: "edit-pen-fill",
        text: '检查',
        count: 0,  // 总数
        isDot: false,
        customIcon: false,
      },
      ],
      dateChoiceShow:false,
			// 企业微信集成 2023-11-9 fsx start
			fContent: [{
				iconPath: require('@/static/add.png'),
				selectedIconPath: require('@/static/add.png'),
				text: '添加计划',
				active: false,
			}],
			fContents: [{
				iconPath: require('@/static/omore.png'),
				selectedIconPath: require('@/static/omore.png'),
				text: '更多',
				active: false,
			}],
			// 企业微信集成 2023-11-9 fsx end
    }
  },
  // 页面加载成功后也要设置一次，用于处理本页面刷新后失效问题
  mounted() {
    this.setRightBtns();
  },
  onShow() {
    if(this.tabIndex != 0){
      this.$refs["mescrollItem1"].refresh();
    }
  },
  methods: {
    // 根据页面返回携带的参数刷新列表
    updateBackState(param){
      // 刷新页面
      param.refresh && (this.tabIndex == 0 ? this.$refs["mescrollItem0"].refresh() : this.$refs["mescrollItem1"].refresh());
    },
    setRightBtns() {
      // 设置右侧标题
      // #ifdef H5-DINGDING
      console.log("设置标题", this.tabIndex);
      if(this.tabIndex == 0){
        this.$deviceApi.setRight("添加计划", () => {
          // 添加特殊区域计划操作
          if (this.tabIndex == 0) {
            this.handlerPlanDetail({});
          }
        }, true, true);
      }else{
        this.$deviceApi.setRight("", () => { }, false, false);
      }
      // #endif
    },
		// 企业微信集成 2023-11-9 fsx start
		fabtrigger(btn) {
			if (btn.index == 0) {
				if (this.tabIndex == 0) {
					this.handlerPlanDetail({});
				} else {
					this.isOpen = true;
				}
			}
		},
		// 企业微信集成 2023-11-9 fsx end
    // 切换tabs刷新列表
    tabsChange(curr) {
      this.tabIndex = curr;
      this.setRightBtns();
      this.tabIndex == 0 ? this.$refs["mescrollItem0"].refresh() : this.$refs["mescrollItem1"].refresh();
    },
    // 添加特殊区域计划
    handlerAddPlan() {
      this.$u.route('/pages/check/undocuEcigarette/addUndocuEcigarettePlan');
    },
    handlerSearchDay(e){
      this.nowDay = e.result;
      this.$refs["mescrollItem1"].refresh();
    },
    // 点击查看计划详情
    handlerPlanDetail(planDetail) {
      this.setRouteParam(planDetail);
      this.handlerAddPlan();
    },
    // 无证电子烟生产企业检查列表查询
    queryCheckRecordList(page){
      return new Promise((resolve, reject) => {
        checkService.queryCheckRecordListByDate(
          {
            page:page.num,
            limit:50, // page.size,
            // orgUuid: this.curUser.user.org.orgUuid,
            planDate: this.nowDay,
          }).then(res => {
          if(res.success){
            let unFinishList = res.data.filter((item) => { return item.checkStatus != M_COMMON_CHECK_STATUS.CHECKED });
            this.list[1].count = (unFinishList || []).length;
            resolve({
              count: res.count,
              data:res.data,
            });
          }else{
            this.$u.toast(res.msg);
            resolve({
              count: 0,
              data:[],
            });
          }
        }).catch(err => {
          this.$u.toast(err);
          resolve({
            count: 0,
            data:[],
          });
        })
      })
    },
    // 无证电子烟列表
    loadPlanData(page) {
      return new Promise((resolve, reject) => {
        const parmas = {
          page:page.num,
          limit:page.size,
          orgUuid: this.curUser.user.org.orgUuid,
          checkStartDate: this.startDate,
          checkEndDate: this.endDate,
        }
        checkService.undocuEcigaretteList(parmas).then(res => {
          if(res.success){
            this.updateSwiperOptionByRes(res.data);
            resolve({
              count: res.count,
              data:res.data,
            });
          }else{
            this.$u.toast(res.msg);
            resolve({
              count: 0,
              data:[],
            });
          }
        }).catch(err => {
          this.$u.toast(err);
          resolve({
            count: 0,
            data:[],
          });
        });
      });
    },
    updateSwiperOptionByRes(arr){
      arr && arr.forEach(itm => {
        itm.show = false;
        itm.swiperDisabled = true;
        itm.swiperOption = [];
        // 草稿状态
        if(itm.status === M_PLAN_STATUS.DRAFT){
          itm.swiperDisabled = false;
          itm.swiperOption.push({
            text: '编辑',
            action:'edit',
            style: { backgroundColor: this.$theme.u_type_primary,},
          },{
            text: '删除',
            action:'del',
            style: { backgroundColor: this.$theme.u_type_error,},
          },);
        }
      });
    },
    swiperClick(index1, index){
      let datas = this.$refs.mescrollItem0.listDatas;
      let cur = -1;
      for (let i = 0; i < datas.length; i++) {
        if(datas[i].checkPlanUuid == index1){
          cur = i;
          break;
        }
      }
      if(cur == -1){
        this.$u.toast("选中数据无效");
        return;
      }
      let opts = datas[cur].swiperOption;
      if(opts[index].action == 'del'){
        this.$modal.confirm('确定要删除吗?',() => {
          checkService.deleteEcigaretteList(datas[cur].checkPlanUuid).then((res) => {
            this.$u.toast(res.msg);
            if(res.success){
              this.$u.toast('删除成功');
              this.$refs["mescrollItem0"].refresh()
            }
          }).catch(err => {
            this.$u.toast(err);
          });
        });
      }else if(opts[index].action == 'edit'){
        this.setRouteParam(datas[cur]);
        this.$u.route('/pages/check/undocuEcigarette/addUndocuEcigarettePlan');
      }
      this.refreshSwiperPlan();
    },
    refreshSwiperPlan() {
      let self = this;
      this.$refs.mescrollItem0.listDatas.map((val, idx) => {
        val.show = false;
        self.$set(val, 'show', false);
        return true;
      });
    },
    swiperOpen(index){
      console.log(index,'index')
      this.$refs.mescrollItem0.listDatas.map((val, idx) => {
        this.$refs.mescrollItem0.listDatas[idx].show = index == val.checkPlanUuid;
      });
    },
    // 日期区间查询条件
    handlerSearchDate(d) {
      this.startDate = d.startDate;
      this.endDate = d.endDate;
      this.rangeDate = d.startDate + "至" + d.endDate;
      this.$refs["mescrollItem0"].refresh();
    },

  },
}
</script>

<style lang="scss" scoped>
.page{padding: 0;}
.content {
  background-color: #F3F4F5;
}
.sticky-header {
  position: fixed;
 /* #ifndef H5-ONLY  */
 top: 0px;
 /* #endif */
 /* #ifdef H5-ONLY  */
 top: 45px;
 /* #endif */
  width: 100%;
  z-index: 999;
}
// /deep/ .u-tabbar__content__item__text {
//   font-size: 15px;
//   top: 30px;
// }
// /deep/.u-tabbar__content__item__button{
//   top: 0px;
// }
</style>
